"""
该文件用于 软件以外的公共操作
"""
import json
import os
import time
import datetime
from utils.read_config import readconfig
from constant import logs_path, ui_log_image_path, temp_cfg_path
from utils.utils_file import modify_cfg
# 装饰器：计时器，打印函数的开始和结束时间
def run_time(func):
    """
    装饰器记录函数所花费时间
    :param func: 需要记录时间的函数
    :return: 固定写法
    """

    def inner(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print("运行{}时间为：{}s".format(func.__name__, str(round((end_time - start_time), 1))))
        return result

    return inner


# 再写个计算内存的装饰器


# 分辨率系数计算
def cal_ratio():
    """
    计算分辨率
    :return: 与1920.1080相比分辨率比例
    """
    width = readconfig.resolution_width
    height = readconfig.resolution_height
    # 不同分辨率下计算宽高的方法
    wr = round(width / 1920, 5)
    hr = round(height / 1080, 5)
    ratio = min(wr, hr)
    return ratio


def get_current_time(format="%Y-%m-%d %H:%M:%S"):
    """
    返回当前指定的时间格式
    :param format: 时间格式
    :return: 当前指定格式的时间
    """
    return datetime.datetime.now().strftime(format)


def init_temp_cfg(module_name):
    temp_info = {
        "log_config": {
            "log_path": "",
            "log_image_path": ""
        },
        "calibrate": {
            "ple": "",
            "comment": "标定相关配置"
        },
        "soft_cfg": {
            "open_testdebug": False,
            "comment": "testdebug的开关状态"
        },
        "orderFlow": {"type": ""},
        "number": 1,
    }
    log_dir = time.strftime(('%Y_%m_%d_%H_%M_%S'), time.localtime())
    log_path = os.path.join(logs_path, log_dir)
    log_image_path = os.path.join(ui_log_image_path, log_dir, '0')
    if "SETUP" in module_name:
        # 设置SETUP时的临时存储信息
        if os.path.exists(temp_cfg_path):
            os.remove(temp_cfg_path)
        temp_info['log_config']['log_path'] = log_path
        temp_info['log_config']['log_image_path'] = log_image_path
        temp_info['is_platform'] = True

        with open(temp_cfg_path, 'w', encoding="utf-8") as f:
            f.write(json.dumps(temp_info, ensure_ascii=False, indent=4))

    elif 'pytest' in module_name:
        if os.path.exists(temp_cfg_path):
            if not modify_cfg(temp_cfg_path, '$.is_platform'):
                os.remove(temp_cfg_path)
            else:
                return
        temp_info['log_config']['log_path'] = log_path
        temp_info['log_config']['log_image_path'] = log_image_path
        with open(temp_cfg_path, 'w', encoding="utf-8") as f:
            f.write(json.dumps(temp_info, ensure_ascii=False, indent=4))
